package com.bdc.memory.dao.impl;

import com.bdc.BdcVar;
import com.bdc.memory.dao.IRecordDao;
import com.bdc.memory.domain.RecordInfo;
import com.google.inject.Inject;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

/**
 * User: shawn
 * Date: 2011-6-20
 * Time: 20:54:37
 */
public class IRecordDaoImpl implements IRecordDao {

    @Inject
    private EntityManager em;

    public long addRecord(RecordInfo info) {
        em.persist(info);
        return info.getRecordId();
    }

    public void delRecord(long recordId) {
        RecordInfo info = em.find(RecordInfo.class, recordId);
        em.remove(info);
    }

    public RecordInfo getRecord(long recordId) {
        return em.find(RecordInfo.class, recordId);
    }

    public List<RecordInfo> getRecordList(long userId, String tag) {
        return getRecordList(userId, tag, -1, -1);
    }

    public List<RecordInfo> getRecordList(long userId, String tag, long from, long count) {
        String sql = "SELECT * FROM record WHERE userId=? AND LOCATE(?, CONCAT(?, tag, ?))!=0";

        boolean isUseLimit = from != -1 && count != -1;
        if (isUseLimit) sql += " LIMIT " + from + "," + count;

        Query query = em.createNativeQuery(sql, RecordInfo.class);
        query.setParameter(1, userId);
        query.setParameter(2, BdcVar.TAG_SEPERATOR + tag + BdcVar.TAG_SEPERATOR);
        query.setParameter(3, BdcVar.TAG_SEPERATOR);
        query.setParameter(4, BdcVar.TAG_SEPERATOR);
        return query.getResultList();
    }
}
